$(function () {
    //暂存单表格
    var temporary_datagrid = $("#receiptBill_datagrid");

    //编辑弹出框
    var edit_dialog = $("#edit_dialog");
    //已选商品信息列表
    var product_datagrid = $("#productInfo_datagrid");
    //所有商品列表
    var allproduct_dialog = $("#allproduct_dialog"); //弹窗
    var allProductInfo_datagrid = $("#allProductInfo_datagrid");//表格
    //公共的车辆info id
    var carInfoId = null;
    //公共的车辆保单号
    var billNumber = null;
    /** =====================================暂存单表格===================================== */
    temporary_datagrid.datagrid({
        url: "/receiptBill/query?state=2",
        fitColumns: true,
        fit: true,
        striped: true,
        pagination: true,
        pageSize: 10,
        pageNumber: 1,
        singleSelect: true,
        toolbar: "#temporary_toolbar",
        columns: [
            [
                {field: 'id', checkbox: true},
                {field: 'number', title: '保险单号', width: 80},
                {
                    field: 'policyClient.id', hidden: true, formatter: function (value, row) {
                    if (row.policyClient) {

                        return row.policyClient.id
                    }
                }
                },
                {
                    field: 'policyClient', title: '投保人', width: 80, formatter: function (value, row) {
                    if (row.policyClient) {
                        return row.policyClient.name;
                    }
                }
                },
                {field: 'vdate', title: '申请日期', width: 80},
                {field: 'limitYear', title: '保险时长', width: 80},
                {
                    field: 'opEmployee', title: '业务员', width: 80, formatter: function (value, row) {
                    if (value) {
                        return value.username;
                    }
                }
                },
                {field: 'totalPrice', title: '投保总金额', width: 80},
                {field: 'state', title: '状态', width: 80, formatter: function (value, row) {
                        if (value) {
                            return "<font color='red'>退回修改</font>";
                        }
                    }
                }
            ]]
    });
    /** ==================================================================================== */
    /** =====================================自定义函数====================================== */

    //所用的点击事件，都通过这个方法来调用对应的方法
    $("a[data-cmd]").click(function () {
        var cmd = $(this).data("cmd");
        methodObject[cmd]();
    });


    var methodObject = {
        //多条件查询
        query: function () {
            //获得当前输入文本框的值
            var clientName = $("#clientName").textbox('getValue')
            var sn = $("#sn").textbox('getValue')
            //加载的时候把参数传递过去
            temporary_datagrid.datagrid('load', {
                clientName: clientName,
                sn: sn
            });
        },
        //退回单中提审到待审核方法
        audit: function () {
            var row = temporary_datagrid.datagrid('getSelected');
            //如果没有选择车辆信息的一条记录
            if (row == null) {
                $.messager.alert('温馨提示', '至少选择一条记录', 'error');
                return;
            }
            $.messager.alert('温馨提示','是否确定要提审核?','info',function () {
                $.post("/receiptBill/changeStateUnaudited", {id:row.id}, function (data) {
                    if (data.success) {
                        $.messager.alert('温馨提示', '提审成功!!!', 'info', function () {
                            temporary_datagrid.datagrid('load');
                        });
                    } else {
                        $.messager.alert('温馨提示', '提审失败!!!', 'error');
                    }
                })
            })
        },
        //查看修改意见的方法
        comment: function () {
            var row = temporary_datagrid.datagrid('getSelected');
            //如果没有选择车辆信息的一条记录
            if (row == null) {
                $.messager.alert('温馨提示', '至少选择一条记录', 'error');
                return;
            }
            $.post("/receiptBill/queryInfo", {id:row.id}, function (data) {
                $.messager.alert('批改意见',data.info);
            })
        },
        //编辑方法
        edit: function () {
            var row = temporary_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert("温馨提示", '至少选择一条数据', 'warning')
                return;
            }
            carInfoId = row.carId;
            billNumber = row.number;
            //传递车辆信息
            $.get('/car/selectCarByBillId', {id: row.car.id}, function (data){
                //维护属性carSizeDetail.id
                //data["loadSize.id"] = data.loadSize.id;
                $("#carinfo_form").form('load',data);
            });
            //传递产品信息
            $.get("/product/selectProductList",{number:row.number},function (data) {
                if (data) {
                    //产品机构id 回显
                    $("#agencyInfo_combobox").combobox('setValue',data[0].company.id);
                    //产品明细数据加载
                    product_datagrid.datagrid('loadData',data);
                }
                //保险年限 row.limitYear
                $("#limitYear_input").textbox('setValue',row.limitYear);
                //总价显示
                $("#totalAmount1").html(row.totalPrice);
            });
            edit_dialog.dialog('open');
            edit_dialog.dialog('center');
        },
        //编辑完成后提交表单
        save: function () {
            $("#carinfo_form").form('submit', {
                url: '/guaranteeBill/editGuaranteeBill',
                onSubmit: function (params) {
                    //维护已选择数据参数
                    var rows = product_datagrid.datagrid('getRows');
                    var ids = $.map(rows, function (value) {
                        return value.id;
                    });
                    var totalAmount =  $("#totalAmount1").html();

                    params["carInfoId"] = carInfoId;
                    params["snNumber"] = billNumber;
                    params["totalAmount"] = totalAmount;
                    params["ids"] = ids;
                    params["limitYear"] = $("#limitYear_input").textbox('getValue');
                },
                success: function (data) {
                    data = $.parseJSON(data)
                    if (data.success) {
                        $.messager.alert('温馨提示', '编辑成功', 'info', function () {
                            edit_dialog.dialog('close');
                            temporary_datagrid.datagrid('reload')
                        });
                    } else {
                        $.messager.alert("温馨提示", data.msg, "warning")
                    }
                }
            })
        },
        //取消的方法
        cancel: function () {
            edit_dialog.dialog('close')
        },
        //刷新的方法
        refresh:function () {
            temporary_datagrid.datagrid('reload')
        }
    };
    /** ======================================编辑弹出框======================================== */
    //编辑弹出框初始化
    edit_dialog.dialog({
        modal: true,
        closed: true,
        title: '编辑保单信息',
        width: 700,
        height: 450,
        buttons: '#edit_buttons',
        top: 200,
        onClose:function () {
            //清楚表单数据
            $("#carinfo_form").form("clear");
        }
    });
    //已选择商品表格
    product_datagrid.datagrid({
        url: '/product/selectProductList',
        fitColumns: true,
        toolbar:'#edit_productInfo_buttons',
        rownumbers: true,
        columns: [[
            {field: 'id', hidden: true},
            {field: 'name', title: '产品名称', width: 100},
            {field: 'annualFee', title: '保险年费', width: 100},
            {field: 'limitYear', title: '年限', width: 100, align: 'right'}
        ]]
    });
    //删除已选商品明细按钮
    $("#edit_productInfo_delete").click(function () {
        var rows =  product_datagrid.datagrid('getSelections');
        //如果没有选择车辆信息的一条记录
        if (rows.length == 0) {
            $.messager.alert('温馨提示', '至少选择一条记录', 'error');
            return;
        }
        for (var i = rows.length - 1; i >= 0; i--) {

            product_datagrid.datagrid('deleteRow', i);
        }
        changeTotalAmount(  $("#limitYear_input").textbox('getValue'))
    });
    //根据输入年份求总额
    $("#limitYear_input").textbox({
        width: 60,
        onChange: function (newValue, oldValue) {
            var rows = $("#productInfo_datagrid").datagrid('getRows');
            var totalAmount = 0;
            for (var i = rows.length - 1; i >= 0; i--) {
                totalAmount = totalAmount + rows[i].annualFee;
            }
            totalAmount = parseFloat(totalAmount * newValue);
            $("#totalAmount1").html(totalAmount);
        }
    });
    //弹出所有商品按钮
    $("#add_linkbutton").linkbutton({
        iconCls: 'icon-add',
        onClick: function () {
            //判断是否选择机构
            var agencyId = $("#agencyInfo_combobox").val();
            console.log(agencyId);
            if (!agencyId) {
                $.messager.alert("温馨提示", "至少选择一个承保机构", "info")
                return
            }
            //加载当前机构的产品信息
            allProductInfo_datagrid.datagrid('load',{agencyId:agencyId});
            allproduct_dialog.dialog('open');
            allproduct_dialog.dialog('center')
        }
    });

    //弹出框
    allproduct_dialog.dialog({
        modal: true,
        closed: true,
        title: '选择保险产品',
        width: 700,
        height: 400,
        onclose: function () {
            product_datagrid.datagrid('loadData ', [])
        }
    });
    //所有商品表格
    allProductInfo_datagrid.datagrid({
        url:'/product/query',
        fit:true,
        fitColumns:true,
        rownumbers:true,
        toolbar:'#chose_buttons',
        pagination: true,
        columns:[[
            {field:'id',checkbox:true},
            {field:'sn', title:'保险编号', width:80},
            {field:'name', title:'产品名称', width:80},
            {field:'company', title:'所属机构', width:80,formatter:function (value, row, index) {
                return value.name;
            }},
            {field:'year', title:'保障年限', width:80},
            {field:'money', title:'保额', width:40},
            {field:'annualFee', title:'年费', width:40},
            {field:'saleState', title:'状态', width:40, formatter:function (value, row, index) {
                return value ?  "<font color='green'>在售</font>" : "<font color='red'>停售</font>";}},
            {field:'deductState', title:'不计免赔', width:80, formatter:function (value, row, index) {
                return value ?  "<font color='green'>是</font>" : "<font color='red'>否</font>";}}
        ]]
    });


})
function changeTotalAmount(year) {
    var rows = $("#productInfo_datagrid").datagrid('getRows');
    var totalAmount = 0;
    for (var i = rows.length - 1; i >= 0; i--) {
        totalAmount = totalAmount + rows[i].annualFee;
    }
    totalAmount = parseFloat(totalAmount * year);
    $("#totalAmount1").html(totalAmount);
}